<template>
  <div>
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人">
        <el-select v-model="form.manager" placeholder="请选择活动区域">
          <el-option v-for="item in list" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{ isEdit?'编辑':'新增' }}</el-button>
        <el-button @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addDepartmentRequest, getDeparmentByIdRequest, updateDepartmentByIdRequest } from '@/api/department'
import { getUserSimpleRequest } from '@/api/employees'
export default {
  props: {
    currentPid: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      list: []
    }
  },
  created() {
    this.getSimple()
    this.getDeparmentById()
  },
  methods: {
    onSubmit() {
      if (this.isEdit) {
        this.updateDepartmentById()
      } else {
        this.addDepartment()
      }
    },
    async getSimple() {
      try {
        const res = await getUserSimpleRequest()
        this.list = res.data
        // console.log(res)
      } catch (err) {
        console.log('错误请求', err)
      }
    },
    cancle() {
      this.$emit('MyCloseEvent')
    },
    // 新增部门
    async addDepartment() {
      try {
        // {...this.form, pid: this.currentPid}
        const res = await addDepartmentRequest({ ...this.form, pid: this.currentPid })
        console.log(res)
        this.$emit('success')
      } catch (err) {
        //
      }
    },
    async getDeparmentById() {
      if (this.isEdit) {
        const res = await getDeparmentByIdRequest(this.currentPid)
        // console.log(res)
        this.form = res.data
      }
    },
    async updateDepartmentById() {
      await updateDepartmentByIdRequest(this.form)
      this.$emit('success')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
